package com.we.risk.registerchanneldeprecated.basicinfo.dim;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;

public class TableUserSource {
    public static final String KFKTABLE = "fdm.hhl01_user_source_1031";
    public static final String QUERYSQL =
            "select uid, "
                    + "origin_source as origin_connect_id, "
                    + "unix_timestamp(date_format(update_time,'yyyy-MM-dd HH:mm:ss')) as update_time "
                    + "from "
                    + KFKTABLE
                    + " where update_time is not null "
                    + "and type = 'H5' "
                    + "and origin_source <> ''";
    public long uid;
    public String origin_connect_id;
    public long update_time;

    public TableUserSource(long uid, String origin_connect_id, long update_time) {
        this.uid = uid;
        this.origin_connect_id = origin_connect_id;
        this.update_time = update_time;
    }

    public TableUserSource() {}

    public static TableUserSource init(long uid) {
        return new TableUserSource(uid, "", -1);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableUserSource.QUERYSQL);
        DataStream<Tuple2<Boolean, TableUserSource>> input =
                tableEnv.toRetractStream(tableRes, TableUserSource.class);

        SingleOutputStreamOperator<String> out =
                input.filter(
                                new FilterFunction<Tuple2<Boolean, TableUserSource>>() {
                                    @Override
                                    public boolean filter(Tuple2<Boolean, TableUserSource> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableUserSource>, Long>() {
                                    @Override
                                    public Long getKey(Tuple2<Boolean, TableUserSource> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableUserSource>, String>() {
                                    ValueState<TableUserSource> userSourceVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        userSourceVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TableUserSource>(
                                                                        "userSourceVState",
                                                                        TableUserSource.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableUserSource> value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        String origin_connect_id = value.f1.getOrigin_connect_id();
                                        long update_time = value.f1.getUpdate_time();

                                        TableUserSource tmpState = userSourceVState.value();
                                        TableUserSource curState =
                                                (tmpState == null
                                                        ? TableUserSource.init(uid)
                                                        : tmpState);

                                        if (update_time > curState.getUpdate_time()
                                                && !origin_connect_id.equals(
                                                        curState.getOrigin_connect_id())) {
                                            JSONObject outJson = new JSONObject();
                                            outJson.put("uid", uid);
                                            outJson.put("origin_connect_id", origin_connect_id);
                                            out.collect(outJson.toString());

                                            curState.update_time = update_time;
                                            curState.origin_connect_id = origin_connect_id;
                                            userSourceVState.update(curState);
                                        }
                                    }
                                });

        return out;
    }

    public long getUid() {
        return uid;
    }

    public String getOrigin_connect_id() {
        return origin_connect_id;
    }

    public long getUpdate_time() {
        return update_time;
    }
}
